using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class BasePanel : MonoBehaviour
{
    private Dictionary<string, List<UIBehaviour>> controlDic = new Dictionary<string, List<UIBehaviour>>();

    // Start is called before the first frame update
    protected virtual void Awake()
    {
        FindUIControl<Button>();
        FindUIControl<Image>();
        FindUIControl<Toggle>();
        FindUIControl<Text>();
        FindUIControl<Slider>();
        FindUIControl<ScrollRect>();
        FindUIControl<InputField>();
    }

    public virtual void ShowMe()
    {

    }
    public virtual void HideMe()
    {

    }
    protected virtual void OnClick(string name)
    {

    }
    protected virtual void OnToggleChange(string buttonName,bool value)
    {

    }
    protected virtual void OnSliderChange(string sliderName, float value)
    {

    }


    protected T GetUIControl<T>(string controlname)where T:UIBehaviour
    {
        if (controlDic.ContainsKey(controlname))
        {
            for (int i = 0; i < controlDic[controlname].Count; i++)
            {
                if (controlDic[controlname][i] is T)
                {
                    return controlDic[controlname][i] as T;
                }
            }
        }

        return null;
    }

    private void FindUIControl<T>() where T:UIBehaviour
    {

        T[] controls = this.GetComponentsInChildren<T>();
        for (int i = 0; i < controls.Length; i++)
        {
            string controlName = controls[i].gameObject.name;
            if (controlDic.ContainsKey(controlName)) 
                controlDic[controlName].Add(controls[i]);
            else 
                controlDic.Add(controls[i].gameObject.name, new List<UIBehaviour>() { controls[i] });


            if (controls[i] is Button)
            {
                (controls[i] as Button).onClick.AddListener(()=> 
                {
                    OnClick(controlName);
                });
            }
            else if(controls[i] is Toggle)
            {
                (controls[i] as Toggle).onValueChanged.AddListener((value) =>
                {
                    OnToggleChange(controlName, value);
                });
            }
            else if (controls[i] is Slider)
            {
                (controls[i] as Slider).onValueChanged.AddListener((value) =>
                {
                    OnSliderChange(controlName, value);
                });
            }
        }
    }
}
